package br.com.nuccitec.jfera.remote {
	import br.com.nuccitec.jfera.event.RemoteEvent;
	import br.com.nuccitec.jfera.response.BusinessResponse;
	import br.com.nuccitec.jfera.response.MessageResponse;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;

	public dynamic class RemoteObjectNucci extends RemoteObject {
		private var remoteEvent:RemoteEvent;
		private var rootUI:Object;

		public function RemoteObjectNucci(destination:String,remoteEvent:RemoteEvent,rootUI:Object) {
			super(destination);
			this.rootUI=rootUI;
			this.showBusyCursor=true;
			this.remoteEvent=remoteEvent;
			addEventListener(ResultEvent.RESULT,callBackFunctionHandler);
			addEventListener(FaultEvent.FAULT,defaultFaultFunctionHandler);
		}

		public function defaultFaultFunctionHandler(event:FaultEvent):void {
			Alert.show("Ocorreu um erro inesperado: "+event.fault.message,"Erro",Alert.OK);
			enableApp();
		}

		public function enableApp():void {
			if(rootUI&&rootUI.hasOwnProperty("enabled")) {
				rootUI.enabled=true;
			}
		}

		protected function callBackFunctionHandler(event:ResultEvent):void {
			enableApp();
			if(event.result is BusinessResponse&&remoteEvent.contentCallBack!=null) {
				remoteEvent.contentCallBack((event.result as BusinessResponse).businessObject);
			} else if(event.result is MessageResponse) {
				var errorMessageResponse:MessageResponse=event.result as MessageResponse;
				if(remoteEvent.messageCallBack!=null) {
					remoteEvent.messageCallBack(errorMessageResponse.title,errorMessageResponse.message);
				} else {
					Alert.show(errorMessageResponse.message,errorMessageResponse.title,Alert.OK);
				}
			} else if(!event.result is BusinessResponse) {
				throw new Error("Not expected object response: "+event.result)
			}
		}
	}
}